package com.company.oa.meeting.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.company.oa.meeting.dto.MeetingDTO;
import com.company.oa.meeting.entity.Meeting;
import com.company.oa.meeting.entity.MeetingParticipant;
import com.company.oa.meeting.mapper.MeetingMapper;
import com.company.oa.meeting.mapper.MeetingParticipantMapper;
import com.company.oa.meeting.service.MeetingService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 会议服务实现类
 */
@Service
public class MeetingServiceImpl extends ServiceImpl<MeetingMapper, Meeting> implements MeetingService {

    @Autowired
    private MeetingParticipantMapper participantMapper;

    @Override
    public IPage<Meeting> getMeetingPage(int page, int size, Meeting meeting) {
        Page<Meeting> pageParam = new Page<>(page, size);
        return baseMapper.selectMeetingPage(pageParam, meeting);
    }

    @Override
    @Transactional
    public boolean createMeeting(MeetingDTO meetingDTO, Long organizerId, String organizerName, Long departmentId, String departmentName) {
        // 检查会议室是否被占用
        List<Meeting> occupiedMeetings = baseMapper.checkRoomOccupied(
                meetingDTO.getRoomId(), 
                meetingDTO.getStartTime(), 
                meetingDTO.getEndTime(),
                null);
        
        if (!occupiedMeetings.isEmpty()) {
            throw new RuntimeException("所选时间段内会议室已被占用");
        }
        
        // 创建会议
        Meeting meeting = new Meeting();
        BeanUtils.copyProperties(meetingDTO, meeting);
        
        meeting.setOrganizerId(organizerId);
        meeting.setOrganizerName(organizerName);
        meeting.setDepartmentId(departmentId);
        meeting.setDepartmentName(departmentName);
        meeting.setStatus(0); // 未开始
        meeting.setCreateTime(LocalDateTime.now());
        meeting.setIsDeleted(0);
        
        boolean result = save(meeting);
        
        // 添加参与人员
        if (result && meetingDTO.getParticipantIds() != null && !meetingDTO.getParticipantIds().isEmpty()) {
            List<MeetingParticipant> participants = new ArrayList<>();
            
            for (Long userId : meetingDTO.getParticipantIds()) {
                MeetingParticipant participant = new MeetingParticipant();
                participant.setMeetingId(meeting.getId());
                participant.setUserId(userId);
                // TODO: 需要通过用户服务获取用户名
                participant.setUserName("用户" + userId);
                participant.setStatus(0); // 未确认
                participant.setCreateTime(LocalDateTime.now());
                
                participants.add(participant);
            }
            
            participantMapper.insertBatch(participants);
            
            // TODO: 发送会议通知
        }
        
        return result;
    }

    @Override
    @Transactional
    public boolean updateMeeting(MeetingDTO meetingDTO) {
        Meeting meeting = getById(meetingDTO.getId());
        if (meeting == null) {
            throw new RuntimeException("会议不存在");
        }
        
        // 只有未开始的会议才能修改
        if (meeting.getStatus() != 0) {
            throw new RuntimeException("只有未开始的会议才能修改");
        }
        
        // 检查会议室是否被占用
        List<Meeting> occupiedMeetings = baseMapper.checkRoomOccupied(
                meetingDTO.getRoomId(), 
                meetingDTO.getStartTime(), 
                meetingDTO.getEndTime(),
                meetingDTO.getId());
        
        if (!occupiedMeetings.isEmpty()) {
            throw new RuntimeException("所选时间段内会议室已被占用");
        }
        
        // 更新会议信息
        BeanUtils.copyProperties(meetingDTO, meeting);
        meeting.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(meeting);
        
        // 更新参与人员
        if (result && meetingDTO.getParticipantIds() != null) {
            // 删除原有参与人员
            LambdaQueryWrapper<MeetingParticipant> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(MeetingParticipant::getMeetingId, meeting.getId());
            participantMapper.delete(wrapper);
            
            // 添加新的参与人员
            if (!meetingDTO.getParticipantIds().isEmpty()) {
                List<MeetingParticipant> participants = new ArrayList<>();
                
                for (Long userId : meetingDTO.getParticipantIds()) {
                    MeetingParticipant participant = new MeetingParticipant();
                    participant.setMeetingId(meeting.getId());
                    participant.setUserId(userId);
                    // TODO: 需要通过用户服务获取用户名
                    participant.setUserName("用户" + userId);
                    participant.setStatus(0); // 未确认
                    participant.setCreateTime(LocalDateTime.now());
                    
                    participants.add(participant);
                }
                
                participantMapper.insertBatch(participants);
                
                // TODO: 发送会议变更通知
            }
        }
        
        return result;
    }

    @Override
    @Transactional
    public boolean cancelMeeting(Long id) {
        Meeting meeting = getById(id);
        if (meeting == null) {
            throw new RuntimeException("会议不存在");
        }
        
        // 只有未开始或进行中的会议才能取消
        if (meeting.getStatus() != 0 && meeting.getStatus() != 1) {
            throw new RuntimeException("只有未开始或进行中的会议才能取消");
        }
        
        meeting.setStatus(3); // 已取消
        meeting.setUpdateTime(LocalDateTime.now());
        
        boolean result = updateById(meeting);
        
        if (result) {
            // TODO: 发送会议取消通知
        }
        
        return result;
    }

    @Override
    public Meeting getMeetingDetail(Long id) {
        return baseMapper.selectMeetingDetail(id);
    }

    @Override
    public IPage<Meeting> getMyOrganizedMeetings(int page, int size, Long organizerId) {
        Page<Meeting> pageParam = new Page<>(page, size);
        
        LambdaQueryWrapper<Meeting> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Meeting::getOrganizerId, organizerId)
               .eq(Meeting::getIsDeleted, 0)
               .orderByDesc(Meeting::getCreateTime);
        
        return page(pageParam, wrapper);
    }

    @Override
    public IPage<Meeting> getMyParticipatedMeetings(int page, int size, Long userId) {
        Page<Meeting> pageParam = new Page<>(page, size);
        return baseMapper.selectUserMeetings(pageParam, userId, null);
    }

    @Override
    @Transactional
    public boolean confirmMeeting(Long meetingId, Long userId) {
        LambdaQueryWrapper<MeetingParticipant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MeetingParticipant::getMeetingId, meetingId)
               .eq(MeetingParticipant::getUserId, userId);
        
        MeetingParticipant participant = participantMapper.selectOne(wrapper);
        if (participant == null) {
            throw new RuntimeException("您不是该会议的参与者");
        }
        
        participant.setStatus(1); // 已确认
        participant.setUpdateTime(LocalDateTime.now());
        
        return participantMapper.updateById(participant) > 0;
    }

    @Override
    @Transactional
    public boolean rejectMeeting(Long meetingId, Long userId) {
        LambdaQueryWrapper<MeetingParticipant> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MeetingParticipant::getMeetingId, meetingId)
               .eq(MeetingParticipant::getUserId, userId);
        
        MeetingParticipant participant = participantMapper.selectOne(wrapper);
        if (participant == null) {
            throw new RuntimeException("您不是该会议的参与者");
        }
        
        participant.setStatus(2); // 已拒绝
        participant.setUpdateTime(LocalDateTime.now());
        
        return participantMapper.updateById(participant) > 0;
    }

    @Override
    public Map<String, Object> getMeetingStatistics(Long userId) {
        Map<String, Object> result = new HashMap<>();
        
        // 我组织的会议数量
        LambdaQueryWrapper<Meeting> organizerWrapper = new LambdaQueryWrapper<>();
        organizerWrapper.eq(Meeting::getOrganizerId, userId)
                       .eq(Meeting::getIsDeleted, 0);
        long organizedCount = count(organizerWrapper);
        result.put("organizedCount", organizedCount);
        
        // 我参与的会议数量
        LambdaQueryWrapper<MeetingParticipant> participantWrapper = new LambdaQueryWrapper<>();
        participantWrapper.eq(MeetingParticipant::getUserId, userId);
        long participatedCount = participantMapper.selectCount(participantWrapper);
        result.put("participatedCount", participatedCount);
        
        // 待确认的会议数量
        LambdaQueryWrapper<MeetingParticipant> pendingWrapper = new LambdaQueryWrapper<>();
        pendingWrapper.eq(MeetingParticipant::getUserId, userId)
                     .eq(MeetingParticipant::getStatus, 0);
        long pendingCount = participantMapper.selectCount(pendingWrapper);
        result.put("pendingCount", pendingCount);
        
        // 今日会议数量
        LocalDateTime today = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
        LocalDateTime tomorrow = today.plusDays(1);
        
        LambdaQueryWrapper<Meeting> todayWrapper = new LambdaQueryWrapper<>();
        todayWrapper.ge(Meeting::getStartTime, today)
                   .lt(Meeting::getStartTime, tomorrow)
                   .eq(Meeting::getIsDeleted, 0);
        long todayCount = count(todayWrapper);
        result.put("todayCount", todayCount);
        
        return result;
    }
} 